<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Infostreams extends Public_Controller
{
	
    public function __construct()
	{

		parent::__construct();
        
		$this->load->model('infostreams_m');
        
        $this->load->helper('text');
		$this->load->helper('date');
		$this->load->helper('infostreams');
        
		$this->lang->load('infostreams');
        
        $this->load->library('form_validation');
        $this->load->library('table');
          
        date_default_timezone_set('Europe/Kiev');
        
        // Get the user ID, if it exists
		if($this->ion_auth->logged_in())
		{
			$this->user_id = $this->current_user->id;
		}

        $this->template
			//->append_js( 'module::jquery.js' )
			//->append_css( 'module::jquery-ui.css' )
            //->append_js( 'module::jquery-ui.min.js' )
			->append_js( 'module::jquery.cookie.js' )
			//->append_metadata('<script src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.2.min.js"></script>')
			->append_js( 'module::raphael-min.js' )
			->append_css( 'module::infostreams.css' )
            //->append_js( 'module::d3.v2.min.js' )
			->append_js( 'module::infostreams.js' );
			
	}

	// blog/page/x also routes here
	public function index()
	{
        
		// Проверяем авторизацию пользователя
		if (!$this->ion_auth->logged_in())
        {
            redirect('users/login/infostreams');
        }
		
        /*
        // Validation rules
		$validation = array(
            array(
  				'field' => 'rynok_id',
  				'label' => 'Код рынка',
  				'rules' => 'xss_clean'
  			),
        );
        
        // Set the validation rules
		$this->form_validation->set_rules($validation);

        
        if ($this->form_validation->run())
		{
		      
           
        }
		else
		{
			// Return the validation error
			$this->data->error_string = $this->form_validation->error_string();
		} 
        */
        
		/*
        $where = array('InfoStreams.id >' => 0);
        if($this->input->post('date_start') !== false):
            $date_start = $this->input->post('date_start');
            //$date_start = strtotime(sprintf('%s %s:%s', $date_start, 0, 0));
            $date_start = strtotime($date_start);
            $where['InfoStreams.created_on >='] = $date_start;
        endif;
        
        if($this->input->post('date_end') !== false):
            $date_end = $this->input->post('date_end');
            //$date_end = strtotime(sprintf('%s %s:%s', $date_end, 0, 0));
            $date_end = strtotime($date_end);
            $where['InfoStreams.created_on <='] = $date_end;
        endif;
        //$this->data->InfoStreams = $this->infostreams_m->getInfoStreams($where);
        $this->data->InfoStreams = $this->infostreams_m->getPropertyValues($where);
        
		*/
		
        if ($this->input->is_ajax_request())
		{
            $status = 'respond';
            $data = array();
             
            /*    
            foreach($this->data->InfoStreams as $row):
                $data[] = array(
                    'id' => ''.$row->source_id.'-'.$row->identifier,
                    'source' => $row->source_title,
                    'title' => $row->title,
                    'text1' => $row->text1,
                    'text2' => date('Y-m-d H:i:s', $row->created_on),
                    'status' => $row->status,
                    'status_color' => ($row->status == 'create') ? '00CCFF' : '33FF00',
                    'created_on' => date('Y-m-d H:i:s', $row->created_on)
                    
                );
            endforeach;
            */
            //$status = time();
            $data = $this->data->InfoStreams;
                          
            return $this->template->build_json(array(
				'status'	 => $status,
				'message'	 => $data
			));
            
        } else {
            
            if ($this->template->layout_exists('infostreams.html'))
    		{
    			$this->template->set_layout('infostreams.html');
    		}
            
            $this->template
    			->title( lang('infostreams_infostreams_title'))
    			->set_breadcrumb( lang('infostreams_infostreams_title'))
    			->set_metadata('description', 'Модуль инфопотоков')
    			->set_metadata('keywords', 'инфо потоки')
    			->build('index', $this->data);
        }
	}
    
    public function Tree(){
        
        if ($this->input->is_ajax_request())
		{
            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'Not authorize!'
                ));
            }
        
            $parent_id = $this->input->post('id');
            
            if(($parent_id === false) or (!is_numeric($parent_id))){
                $parent_id = 0;
            }
            
            $parent_id = $parent_id + 0;

            $status = 'ok';
            $data = $this->infostreams_m->get_InfostreemTree($parent_id);
            
            return $this->template->build_json(array(
				'status'	 => $status,
				'message'	 => $data
			));
            
        } else {
            
            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
              redirect('users/login/infostreams');
              show_error('error. Not authorize!');
            }

            //show_error('error. Only Ajax request!');
            //print_r($this->infostreams_m->get_InfostreemTree(0));
            $data = $this->infostreams_m->get_InfostreemTree(0);
            print_r($data);
            //echo 'hello';
        }     
    }

    public function Add(){
        
        // Проверяем авторизацию пользователя
        //if (!$this->user)
        //{
        //  redirect('users/login');
        //  show_error('error. Not authorize!');
        //}
        
        if ($this->input->is_ajax_request())
        {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'Not authorize!'
                ));
            }
            
            $post = $this->input->post(NULL, true);
            $parent_id = $this->input->post('parent');
            //$version = $this->input->post('version');
            $nested_level = $this->input->post('nested_level');
            $post['version'] = 1;
            if(($parent_id === false) or (!is_numeric($parent_id))){
                $parent_id = 0;
                $post['parent'] = $parent_id;
            }
            
            $parent_id = $parent_id + 0;
            $post['level'] = $this->infostreams_m->getLevelParent($parent_id);
            if(($nested_level === true) OR ($nested_level === 'true')){
                $post['level']++;    
            }
            
            $last_id = $this->infostreams_m->Add($post);
            		
            if($last_id > 0){
                $status = 'ok-blja';
                $data = array('id' => $last_id);
            } else {
                $status = 'error';
                $data = array('id' => $last_id);
            }
            //$data = $this->infostreams_m->InfostreemAdd($parent_id);
            
            return $this->template->build_json(array(
                'status'     => $status,
                'message'    => $data
            ));
            
        } else {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
              redirect('users/login/infostreams');
              show_error('error. Not authorize!');
            }

            //show_error('error. Only Ajax request!');
            //print_r($this->infostreams_m->get_InfostreemTree(0));
            $data = $this->infostreams_m->get_InfostreemTree(0);
            print_r($data);
            //echo 'hello';
        }     
    }

    public function Edit(){
        
        // Проверяем авторизацию пользователя
        //if (!$this->user)
        //{
        //  redirect('users/login');
        //  show_error('error. Not authorize!');
        //}
        
        if ($this->input->is_ajax_request())
        {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'Not authorize!'
                ));
            }
        
            $post = $this->input->post(NULL, true);
            $id = $this->input->post('id');
            $version = $this->input->post('version');
            $post['version'] = $version + 1;
            
            if(($id === false) or (!is_numeric($id))){
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'fill in the required parameter "id"'
                ));
            }
            
            if(($version === false) or (!is_numeric($version))){
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'fill in the required parameter "version"'
                ));
            }
            
            $check_version = $this->infostreams_m->check_version($id, $version);
            if(($check_version === false)){
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'error! you can not edit, version of object is change!'
                ));
            }

            $status = 'ok';
            $data = $this->infostreams_m->update($id, $post);
            if($data == false){
                $status = 'error';
            }
            
            return $this->template->build_json(array(
                'status'     => $status,
                'message'    => $data
            ));
            
        } else {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
              redirect('users/login/infostreams');
              show_error('error. Not authorize!');
            }

            //show_error('error. Only Ajax request!');
            //print_r($this->infostreams_m->get_InfostreemTree(0));
            $data = $this->infostreams_m->get_InfostreemTree(0);
            print_r($data);
            //echo 'hello';
        }     
    }

    public function Delete(){
        
        // Проверяем авторизацию пользователя
        //if (!$this->user)
        //{
        //  redirect('users/login');
        //  show_error('error. Not authorize!');
        //}
        
        if ($this->input->is_ajax_request())
        {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'Not authorize!'
                ));
            }
        
            $id = $this->input->post('id');
            
            if(($id === false) or (!is_numeric($id))){
                return $this->template->build_json(array(
                    'status'     => 'error',
                    'message'    => 'fill in the required parameter "id"'
                ));
            }
            
            $status = 'ok';
            $data = $this->infostreams_m->delete($id);
            if($data == false){
                $status = 'error';
            }
            
            return $this->template->build_json(array(
                'status'     => $status,
                'message'    => $data
            ));
            
        } else {

            // Проверяем авторизацию пользователя
            if (!$this->ion_auth->logged_in())
            {
              redirect('users/login/infostreams');
              show_error('error. Not authorize!');
            }

            //show_error('error. Only Ajax request!');
            //print_r($this->infostreams_m->get_InfostreemTree(0));
            $data = $this->infostreams_m->get_InfostreemTree(0);
            print_r($data);
            //echo 'hello';
        }     
    }
        
}

?>